import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store'
import MainLayout from '../layouts/MainLayout.vue'

const routes = [
  {
    path: '/login',
    name: 'UserLogin',
    component: () => import('../views/UserLogin.vue'),
    meta: { requiresAuth: false, title: '登录' }
  },
  {
    path: '/register',
    name: 'UserRegister',
    component: () => import('../views/UserRegister.vue'),
    meta: { requiresAuth: false, title: '注册' }
  },
  {
    path: '/',
    component: MainLayout,
    children: [
      {
        path: '',
        name: 'HomePage',
        component: () => import('../views/HomePage.vue'),
        meta: { requiresAuth: true, title: '首页' }
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('../views/UserProfile.vue'),
        meta: { requiresAuth: true, title: '个人信息' }
      },
      {
        path: 'meal-record',
        name: 'MealRecord',
        component: () => import('../views/MealRecord.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'meal-plan',
        name: 'MealPlan',
        component: () => import('../views/MealPlan.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'nutrition',
        name: 'NutritionAnalysis',
        component: () => import('../views/NutritionAnalysis.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'recipes',
        name: 'RecipeList',
        component: () => import('../views/RecipeList.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'goals',
        name: 'GoalSetting',
        component: () => import('../views/GoalSetting.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'settings',
        name: 'SystemSettings',
        component: () => import('../views/SystemSettings.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'food',
        name: 'FoodSearch',
        component: () => import('../views/FoodSearch.vue'),
        meta: { requiresAuth: true }
      }
    ]
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局路由守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  const userId = localStorage.getItem('userId')

  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 膳食推荐系统` : '膳食推荐系统'

  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    if (!token || !userId) {
      // 未登录，重定向到登录页
      store.commit('user/CLEAR_USER')
      next('/login')
      return
    }

    try {
      // 验证用户信息
      if (!store.state.user.userInfo) {
        await store.dispatch('user/getUserInfo')
      }
      next()
    } catch (error) {
      console.error('验证用户信息失败:', error)
      store.commit('user/CLEAR_USER')
      next('/login')
    }
  } else {
    // 如果访问登录/注册页面且已登录，重定向到首页
    if ((to.path === '/login' || to.path === '/register') && token && userId) {
      // 恢复用户信息
      if (!store.state.user.userInfo) {
        store.commit('user/SET_USER_INFO', JSON.parse(localStorage.getItem('userInfo')))
      }
      next('/')
      return
    }
    next()
  }
})

export default router 